import { API_CONFIG, getSessionId, createFormData } from './config.js';


// 本地缓存上传的文件
const cachedFiles = new Map();

// 上传文件到本地缓存
export const uploadFiles = async (files) => {
  console.log('uploadFiles 被调用, 文件:', files)

  try {
    const sessionId = getSessionId();
    console.log('sessionId:', sessionId)

    const newFiles = Array.from(files).map(file => ({
      name: file.name,
      size: file.size,
      type: file.type,
      lastModified: file.lastModified,
      file: file
    }));

    console.log('newFiles:', newFiles)

    // 获取现有缓存文件或创建新数组
    const existingFiles = cachedFiles.get(sessionId) || [];
    console.log('现有缓存文件:', existingFiles)
    
    // 合并文件，避免重复
    const mergedFiles = [...existingFiles];
    newFiles.forEach(newFile => {
      if (!existingFiles.some(f => f.name === newFile.name && f.lastModified === newFile.lastModified)) {
        mergedFiles.push(newFile);
      }
    });

    cachedFiles.set(sessionId, mergedFiles);
    console.log('当前缓存文件:', mergedFiles);
    return { success: true, count: mergedFiles.length };
  } catch (error) {
    console.error('缓存文件时出错:', error);
    throw error;
  }
};

// 发送缓存文件到后端
export const sendFilesToBackend = async (onProgress = null) => {
  const sessionId = getSessionId();
  const files = cachedFiles.get(sessionId);

  console.log('调用 sendFilesToBackend, sessionId:', sessionId)
  console.log('缓存文件:', files)

  if (!files || files.length === 0) {
    console.error('没有可发送的缓存文件')
    throw new Error('没有可发送的缓存文件');
  }

  console.log('准备上传的缓存文件:', files);
  
  try {
    // 确保formData包含所有文件
    const formData = new FormData();
    files.forEach(fileObj => {
      formData.append('files', fileObj.file);
    });
    formData.append('sessionId', sessionId);
    
    const uploadUrl = `${API_CONFIG.baseUrl}/upload`;
    console.log('上传URL:', uploadUrl);
    console.log('上传文件数量:', files.length);

    const response = await fetch(uploadUrl, {
      method: 'POST',
      body: formData
    });

    console.log('HTTP响应状态:', response.status, response.statusText);

    if (!response.ok) {
      const errorText = await response.text();
      console.error('上传失败响应:', errorText);
      throw new Error(`文件上传失败: ${response.status} - ${errorText}`);
    }
    
    const result = await response.json();
    console.log('后端返回结果:', result);
    console.log('result.outputPath:', result.outputPath);
    console.log('result.generatedFile:', result.generatedFile);
    console.log('result所有属性:', Object.keys(result));

    // 只有在上传成功后才删除缓存
    if (result && result.success !== false) {
      cachedFiles.delete(sessionId);
      console.log(`已成功上传并删除session ${sessionId}的缓存文件`);

      // 获取生成的文件路径
      // 根据后端日志，文件生成在 src/main/resources/generated/ 目录下
      if (result.outputPath) {
        // 如果后端返回了outputPath，使用它作为文件路径
        // 将路径转换为前端可访问的URL
        const fileName = result.outputPath.split(/[\/\\]/).pop(); // 兼容Windows和Linux路径
        const encodedFileName = encodeURIComponent(fileName); // URL编码中文文件名
        result.filePath = `http://localhost:35005/api/generated/${encodedFileName}`;
        console.log('从outputPath设置文件路径:', result.filePath);
      } else if (result.generatedFile) {
        const encodedFileName = encodeURIComponent(result.generatedFile); // URL编码
        result.filePath = `http://localhost:35005/api/generated/${encodedFileName}`;
        console.log('从generatedFile设置文件路径:', result.filePath);
      } else if (result.filePath) {
        // 如果后端已经返回了filePath，直接使用
        console.log('使用后端提供的filePath:', result.filePath);
      } else {
        // 如果后端没有返回文件路径，构造一个基于时间戳的路径
        const timestamp = new Date().getTime();
        const fileName = `行政处罚立案审批表_${timestamp}.docx`;
        const encodedFileName = encodeURIComponent(fileName); // URL编码
        result.filePath = `http://localhost:35005/api/generated/${encodedFileName}`;
      }
    } else {
      console.warn('后端返回上传可能未成功，保留缓存文件');
    }
    
    return result;
  } catch (error) {
    console.error('发送文件到后端时出错，保留缓存文件:', error);
    throw error;
  }
};

// 获取文件历史列表
export const getFileHistoryList = async () => {
  try {
    const sessionId = getSessionId();
    
    const response = await fetch(`${API_CONFIG.baseUrl}/history/${sessionId}`);
    
    if (!response.ok) {
      throw new Error(`获取文件历史列表失败: ${response.status}`);
    }
    
    return await response.json();
  } catch (error) {
    console.error('获取文件历史列表时出错:', error);
    throw error;
  }
};

// 获取单个文件历史
export const getFileHistory = async (fileId) => {
  try {
    const sessionId = getSessionId();
    
    const response = await fetch(`${API_CONFIG.baseUrl}/history/${sessionId}/${fileId}`);
    
    if (!response.ok) {
      throw new Error(`获取文件历史失败: ${response.status}`);
    }
    
    return await response.json();
  } catch (error) {
    console.error('获取文件历史时出错:', error);
    throw error;
  }
};

// 下载文件
export const downloadFile = async (fileId, filename = 'document') => {
  try {
    const sessionId = getSessionId();
    
    const response = await fetch(`${API_CONFIG.baseUrl}/download/${sessionId}/${fileId}`);
    
    if (!response.ok) {
      throw new Error(`下载文件失败: ${response.status}`);
    }
    
    // 创建下载链接
    const blob = await response.blob();
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    
    // 清理
    setTimeout(() => {
      document.body.removeChild(a);
      window.URL.revokeObjectURL(url);
    }, 0);
    
  } catch (error) {
    console.error('下载文件时出错:', error);
    throw error;
  }
};

// 下载Word文件
export const downloadWordFile = async (fileId, filename = 'document.docx') => {
  try {
    const sessionId = getSessionId();
    
    const response = await fetch(`${API_CONFIG.baseUrl}/download-word/${sessionId}/${fileId}`);
    
    if (!response.ok) {
      throw new Error(`下载Word文件失败: ${response.status}`);
    }
    
    // 创建下载链接
    const blob = await response.blob();
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    
    // 清理
    setTimeout(() => {
      document.body.removeChild(a);
      window.URL.revokeObjectURL(url);
    }, 0);
    
  } catch (error) {
    console.error('下载Word文件时出错:', error);
    throw error;
  }
};

// 填充案件表单
export const fillCaseForm = async (jsonData, templateName) => {
  try {
    const response = await fetch(`${API_CONFIG.baseUrl}/fill-case-form`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        jsonData,
        templateName
      })
    });

    if (!response.ok) {
      throw new Error(`填充案件表单失败: ${response.status}`);
    }

    return await response.json();
  } catch (error) {
    console.error('填充案件表单时出错:', error);
    throw error;
  }
};

// 生成笔录 - 基于立案审批表内容
export const generateInterrogationRecord = async (caseApprovalContent, sessionId = null) => {
  const actualSessionId = sessionId || getSessionId();

  console.log('调用 generateInterrogationRecord, sessionId:', actualSessionId)
  console.log('立案审批表内容长度:', caseApprovalContent ? caseApprovalContent.length : 'null')

  if (!caseApprovalContent) {
    console.error('没有提供立案审批表内容')
    throw new Error('没有提供立案审批表内容');
  }

  try {
    const uploadUrl = `${API_CONFIG.baseUrl}/generate-interrogation`;
    console.log('笔录生成URL:', uploadUrl);

    const requestBody = {
      sessionId: actualSessionId,
      caseApprovalContent: caseApprovalContent
    };

    const response = await fetch(uploadUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(requestBody)
    });

    console.log('HTTP响应状态:', response.status, response.statusText);

    if (!response.ok) {
      const errorText = await response.text();
      console.error('笔录生成失败响应:', errorText);
      throw new Error(`笔录生成失败: ${response.status} - ${errorText}`);
    }

    const result = await response.json();
    console.log('后端返回结果:', result);
    console.log('result.wordPath:', result.wordPath);
    console.log('result.htmlPath:', result.htmlPath);
    console.log('result所有属性:', Object.keys(result));

    return result;
  } catch (error) {
    console.error('生成笔录时出错:', error);
    throw error;
  }
};